<?php 

// Conecta com o banco de dados
include 'includes/conectionMySql.inc';

@$page = $_GET['page']; // get the requested page
@$limit = $_GET['rows']; // get how many rows we want to have into the grid
@$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
@$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1;
if(!$limit) $limit =20;
if(!$page) $page =1;

//array to translate the search type
$ops = array(
    'eq'=>'=', //equal
    'ne'=>'<>',//not equal
    'lt'=>'<', //less than
    'le'=>'<=',//less than or equal
    'gt'=>'>', //greater than
    'ge'=>'>=',//greater than or equal
    'bw'=>'LIKE', //begins with
    'bn'=>'NOT LIKE', //doesn't begin with
    'in'=>'LIKE', //is in
    'ni'=>'NOT LIKE', //is not in
    'ew'=>'LIKE', //ends with
    'en'=>'NOT LIKE', //doesn't end with
    'cn'=>'LIKE', // contains
    'nc'=>'NOT LIKE'  //doesn't contain
);

function getWhereClause($col, $oper, $val){
    global $ops;
    if($oper == 'bw' || $oper == 'bn') $val .= '%';
    if($oper == 'ew' || $oper == 'en' ) $val = '%'.$val;
    if($oper == 'cn' || $oper == 'nc' || $oper == 'in' || $oper == 'ni') $val = '%'.$val.'%';
	
	
		
		$wh = "AND $col {$ops[$oper]} '$val' ";
		 
	
    return $wh;
}

$where = ""; //if there is no search request sent by jqgrid, $where should be empty
$searchField = isset($_GET['searchField']) ? $_GET['searchField'] : false;
$searchOper = isset($_GET['searchOper']) ? $_GET['searchOper']: false;
$searchString = isset($_GET['searchString']) ? $_GET['searchString'] : false;
if (@$_GET['_search'] == 'true') {
    $where = getWhereClause($searchField,$searchOper,addslashes($searchString));
}

$result = mysql_query("select count(*) as count FROM email_config email inner join email_nivel nivel on email.nivel_email =  nivel.id WHERE 1 " . $where );
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];

if( $count >0 ){
	$total_pages = ceil($count/$limit);
}else{
	$total_pages = 0;
}
echo $where;
if($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
$SQL = "SELECT email.id, email.email, nivel.nivel FROM email_config email inner join email_nivel nivel on email.nivel_email =  nivel.id WHERE 1 ".$where." order by $sidx $sord limit $start, $limit";

$result = mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error());

@$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;

$i=0;

while($row = mysql_fetch_array($result)){
	$responce->rows[$i]['id']=$row[0];
	$responce->rows[$i]['cell']=array($row[0],$row[1],$row[2]);
	$i++;
}
mysql_close($db);
echo json_encode($responce);

?>